const API = require('../../utils/api')
const app = getApp()

// 引入SDK核心类，js文件根据自己业务，位置可自行放置
var QQMapWX = require('../../common/qqmap-wx-jssdk1.2/qqmap-wx-jssdk.min')
var qqmapsdk

Page({
    /**
     * 页面的初始数据
     */
    data: {
        inviterUserId:'',
        tagCurrent: 1,
        screenList: [
            {
                title: '城市',
                children: ['全部','杭州'],
                current: 0,
            },
            {
                title: '地区',
                children: ['全部','上城区','下城区','西湖区','江干区','拱墅区','滨江区','萧山区','余杭区','临安区','富阳区','建德','桐庐县','淳安县'],
                current: 0,
            },
            {
                title: '面积',
                children: ['全部', '0-100', '100-200', '200-300', '300-500', '500-1000', '1000-5000'],
                current: 0,
            },
            {
                title: '佣金',
                children: ['全部', '0-999', '1000-1999', '2000-2999', '3000-9999', '10000-99999'],
                current: 0,
            },
        ],
        parkQuery:{
            bokerageMax:'', //最大佣金
            bokerageMin:'', //最小佣金
            areaId:'', //房源范围
            region:'', //地区
            city:'', //城市
            pageSize: 10,
            pageNum: 1,
        },
        parkList:[],
        reachBottomShow: false,
        //canvas
        canvasShow:false,
        maskShow: false,
        shareContent: null
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        // 实例化API核心类
        qqmapsdk = new QQMapWX({
            key: 'DXTBZ-YDREU-SD7VG-BRWIV-ELVTV-OHF4Z'
        });

        let that = this
        app.login(userData)
        function userData(data){
            that.setData({
                userInfo:data,
                inviterUserId:app.globalData.inviterUserId
            })
        }
        that.get_back_garden_house_area_list()
        that.get_task_house_list()
    },
    housingResourceChange (event) {
        this.data.shareContent = event.detail
    },
    /**
     * 页面触底
     */
    onReachBottom:function(){
        let that = this
        let pageNum = this.data.parkQuery.pageNum
        if( this.data.reachBottomShow ){
            if( that.data.tagCurrent == 1 ){
                pageNum++
                this.setData({
                    ['parkQuery.pageNum']: pageNum
                })
                that.get_task_house_list()
            }
            console.log('加载下一页', pageNum)
        }else{
            console.log('到底了',pageNum)
        }
    },

    /**
     * 页面隐藏
     */
    onHide:function(){
        this.hiddenMask()
    },

    /**
     * 接口 - 园区列表
     */
    get_task_house_list:function(){
        let that = this
        wx.showLoading({
          title: '加载中',
          mask: true
        })

        let query = {}
        for( let key in that.data.parkQuery ){
            if( that.data.parkQuery[key] && that.data.parkQuery[key] != '全部' ){
                query[key] = that.data.parkQuery[key]
            }
        }
        console.log('参数', query)

        API.get_task_house_list( query ).then( res => {
            if( res.code == 200 ){
                that.setData({
                    parkList: [...that.data.parkList,...res.rows],
                })
                if( res.rows.length == 10 ){
                    that.setData({
                        reachBottomShow: true
                    })
                }else{
                    that.setData({
                        reachBottomShow: false
                    })
                }
            }else{
                wx.showToast({
                  title: res.msg,
                  icon: 'none'
                })
            }
            
            setTimeout(() => {
                wx.hideLoading()
            }, 1000);
        })
    },

    /**
     * 接口 - 房源面积
     */
    get_back_garden_house_area_list:function(){
        let that = this
        API.get_back_garden_house_area_list().then( res => {
            let screenList = that.data.screenList
            let rows = res.rows
            rows.unshift({
                id: '',
                scope: '全部'
            })
            screenList[2] = {
                title: '面积',
                current: 0,
                children: rows
            }
            that.setData({
                screenList
            })
            console.log(that.data.screenList)
        })
    }, 

    /**
     * 事件 - 园区筛选改变
     */
    screenChange:function(e){
        let that = this
        let index = e.currentTarget.id
        let childrenIndex = e.detail.value

        //清空列表 重置指针
        let screenList = this.data.screenList
        screenList[index].current = childrenIndex
        this.setData({
            parkList: [],
            ['parkQuery.pageNum']: 1,
            screenList
        })

        console.log('筛选', index, childrenIndex)
        if( index == 0 ){ //城市
            this.setData({
                // ['parkQuery.city']: that.data.screenList[index].children[childrenIndex],
                ['parkQuery.city']: that.data.screenList[index].children[childrenIndex]
            })
        }else if( index == 1 ){ //地区
            this.setData({
                ['parkQuery.region']: that.data.screenList[index].children[childrenIndex]
            })
        }else if( index == 2 ){ //面积
            this.setData({
                ['parkQuery.areaId']: that.data.screenList[index].children[childrenIndex].id
            })
        }else if( index == 3 ){ //佣金
            console.log(that.data.screenList[index].children[childrenIndex])
            let value = that.data.screenList[index].children[childrenIndex].split('-')
            this.setData({
                ['parkQuery.bokerageMin']: value[0],
                ['parkQuery.bokerageMax']: value[1]
            })
        }
        
        this.get_task_house_list()
    },

    /**
     * 事件 - 地图导航
     */
    openLocation:function(e){
        let that = this
        let location = e.currentTarget.dataset.location
        //调用地址解析接口
        qqmapsdk.geocoder({
            //获取表单传入地址
            address: location, 
            success: function(res) {
                console.log(res);
                var result = res.result;
                var latitude = result.location.lat; //维度
                var longitude = result.location.lng; //经度

                // that.getReverseGeocoder(latitude, longitude)
                
                wx.openLocation({
                    latitude,
                    longitude,
                    name: e.currentTarget.dataset.name,
                    address: location,
                    scale: 18
                })
            },
            fail: function(error) {
                console.error(error);
                wx.showToast({
                  title: '获取定位失败,请稍后重试',
                  icon:'none'
                })
            },
        })
    },

    /**
     * 地图 - 获取坐标位置描述
     */
    getReverseGeocoder:function(latitude, longitude){
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            success:function(res){
                console.log( '获取坐标位置描述', res )
            }
        })
    },

    /**
     * 路由 - 详情
     */
    routeHouse:function(e){
        let that = this
        let hasUserInfo = app.globalData.hasUserInfo
        if( !hasUserInfo ){
            wx.reLaunch({
              url: '/pages/login/login?back=/pages/task/task',
            })
            return
        }
    
        //路由跳转
        let item = e.currentTarget.dataset.item
        // console.log(item)
        wx.navigateTo({
            url: '/pages/park/house/detail?id=' + item.id + '&gardenId=' + item.gardenId
        })
    },

    /**
     * 分享 - 显示菜单
     */
    share:function(e){
        // console.log( e.currentTarget.dataset.item )
        this.setData({
            maskShow: true,
            shareContent: e.currentTarget.dataset.item 
        })
    },

    /**
     * 分享 - 隐藏菜单
     */
    hiddenMask:function(e){
        this.setData({
            maskShow: false
        })
    },

    /**
     * 事件 - canvas分享 园区
     */
    sharePark:function(e){
        this.setData({
            shareData: e.currentTarget.dataset.item,
            page:'pages/park/park',
            canvasId: 'shareImg' + Date.parse(new Date()),
            canvasShow: true,
        })
        console.log('打开组件画图',e.currentTarget.dataset.item)
    },

    /**
     * 分享
     */
    onShareAppMessage: function () {
        let shareContent = this.data.shareContent
        // console.log(shareContent)
        return {
            title: '(' + shareContent.houseArea + '㎡' + shareContent.fitmentCase + ')' + shareContent.gardenName,
            imageUrl: shareContent.houseImg,
            path: '/pages/park/park?id=' + shareContent.gardenId + '&inviterUserId=' + app.globalData.userInfo.id
        }
    },

    /**
     * 生成海报
     */
    creatCanvas:function(){
        console.log('生成海报')
        let shareContent = this.data.shareContent
        console.log(shareContent)
        this.setData({
            canvasId: 'shareImg' + Date.parse(new Date()),
            shareData: shareContent,
            page:'pages/park/park',
            canvasShow: true,
        })
        console.log('打开组件画图',shareContent)
    },
})